package org.restoran.model;

import javax.persistence.*;
import java.io.Serializable;

/**
 *
 * Simple object that contains unique composite key {@link ItemOrderPk} and amount.
 *
 * */
@AssociationOverrides({
        @AssociationOverride(name = "pk.order",
                joinColumns = @JoinColumn(name = "ORDER_ID")),
        @AssociationOverride(name = "pk.item",
                joinColumns = @JoinColumn(name = "ITEM_ID")) })
@Entity
@javax.persistence.Table(name = "ORDERS_ITEM")
public class ItemOrder implements Serializable {

    public ItemOrder() {
        count = 1;
    }

    @EmbeddedId
    private ItemOrderPk pk = new ItemOrderPk();

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    @Column(name = "CAPACITY", nullable = false)
    private Integer count;

    public void addItemOrder(Item i, Order o) {
        pk.setItem(i);
        pk.setOrder(o);

        o.getItems().add(this);
    }

    public ItemOrderPk getPk() {
        return pk;
    }

    public void setPk(ItemOrderPk pk) {
        this.pk = pk;
    }

    public Item getItem() {
        return pk.getItem();
    }

    public Order getOrder() {
        return pk.getOrder();
    }

    public void setOrder(Order order) {
        pk.setOrder(order);
    }

    public void setItem(Item item) {
        pk.setItem(item);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ItemOrder)) return false;

        ItemOrder that = (ItemOrder) o;
        return (pk != null ? pk.equals(that.pk) : that.pk != null);

    }

    @Override
    public int hashCode() {
        int result = pk != null ? pk.hashCode() : 0;
        result = 31 * result + (count != null ? count.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "{pk= " + pk + ", count=" + count + "}";    }
}
